package com.learn.thread;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author mark
 * @description: 线程协作
 * @date 2025-11-06
 * @version: 1.0
 */
/*
 生产者，消费者，容器，操作对象
 */
public class TestThreadTeamwork {
    public static void main(String[] args) {
        PCCache pcCache=new PCCache();
        new Thread(new Producer(pcCache)).start();
        new Thread(new Consumer(pcCache)).start();
    }
}

/**
 * @description： 肯德基的鸡
 * @time 2025-11-6
 */
class Chicken {

    private int id;

    public Chicken(int id) {
        this.id = id;
    }
}

class Producer implements Runnable{
    private PCCache pcCache;

    public Producer(PCCache pcCache) {
        this.pcCache = pcCache;
    }

    @Override
    public void run() {

        for (int i = 1; i <= 100; i++) {
            pcCache.create(i);
        }
    }
}

class Consumer implements Runnable{
    private PCCache pcCache;

    public Consumer(PCCache pcCache) {
        this.pcCache = pcCache;
    }

    @Override
    public void run() {

        for (int i = 1; i <= 100; i++) {
            this.pcCache.eat(i);
        }
    }


}

class PCCache {
    private static Map<Integer, Chicken> cacheChicken = new HashMap<>();
    public synchronized  void create(int orderId) {
        while (cacheChicken.size() >= 10) {          // 2. while 防止虚假唤醒
            try {
                this.wait();                         // 3. 在锁内 wait 合法
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();  // 保留中断状态
            }
        }

        System.out.println("开始生产肯德基 " + orderId);
        cacheChicken.put(orderId, new Chicken(orderId));
        this.notifyAll();                            // 4. 唤醒等待的吃货


    }

    public synchronized void eat( int id) {
        while (!cacheChicken.containsKey(id)) {      // 2. while 防止虚假唤醒
            try {
                this.wait();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
        System.out.println("开始消费肯德基 " + id);
        cacheChicken.remove(id);
        this.notifyAll();
    }
}